<template>
  <Dialog 
    :title="dialogTitle" 
    v-model="dialogVisible" 
    width="520px"
    class="account-balance-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item 
        label="商家名称" 
        prop="merchantId" 
        class="form-item"
        required
      >
        <el-select 
          v-model="formData.merchantId" 
          placeholder="请选择商家" 
          filterable 
          :loading="merchantLoading"
          class="w-full"
          popper-class="merchant-select-dropdown"
          clearable
          @focus="handleSelectFocus"
          @visible-change="handleVisibleChange"
          @filter-method="handleSearch"
        >
          <el-option
            v-for="item in merchantList"
            :key="item.id"
            :label="item.merchantName"
            :value="item.id"
          />
          <template #dropdown>
            <div class="merchant-select-content">
              <div v-if="merchantList.length === 0" class="merchant-empty">
                <el-empty description="暂无数据" />
              </div>
              <div v-if="hasMore && !merchantLoading" class="merchant-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span class="loading-text">加载更多...</span>
              </div>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item 
        label="账户类型" 
        prop="accountType" 
        class="form-item"
        required
      >
        <el-select 
          v-model="formData.accountType" 
          placeholder="请选择账户类型"
          class="w-full"
          popper-class="account-select-dropdown"
          @change="handleAccountTypeChange"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.JULIANG_ACCOUNT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item 
        label="巨量账户ID" 
        prop="advertiserId" 
        class="form-item"
      >
        <el-input 
          v-model="formData.advertiserId" 
          placeholder="请输入巨量账户ID" 
          class="w-full"
        />
      </el-form-item>
      <el-form-item 
        label="折扣类型" 
        prop="rechargeDiscountType" 
        class="form-item"
      >
        <el-radio-group v-model="formData.rechargeDiscountType" class="radio-group">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.JULIANG_RECHARGE_DISCOUNT_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
        <div class="form-tip">选择充值时的折扣类型，影响充值金额计算。建议根据业务需求选择合适的折扣类型。此字段为必填项。</div>
      </el-form-item>
      <el-form-item 
        v-if="formData.accountType === 1"
        label="返利比例" 
        prop="rebateRatio" 
        class="form-item"
      >
        <el-input 
          v-model="formData.rebateRatio" 
          placeholder="请输入返利比例"
          class="w-full"
          type="number"
          :min="0"
          :max="100"
          :step="0.01"
        >
          <template #append>%</template>
        </el-input>
        <div class="form-tip">例如：5 表示 5% 的返利，只有主账号才有此字段。子账号不显示此字段。此字段为可选项。</div>
      </el-form-item>
      <el-form-item 
        v-if="formType === 'update'"
        label="状态" 
        prop="status" 
        class="form-item"
      >
        <el-radio-group v-model="formData.status" class="radio-group">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row v-if="formType === 'update'" :gutter="16">
        <el-col :span="12">
          <el-form-item 
            label="账户余额" 
            class="form-item"
          >
            <el-input
              v-model="formData.balance"
              disabled
              class="w-full disabled-input"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item 
            label="冻结金额" 
            class="form-item"
          >
            <el-input
              v-model="formData.frozenAmount"
              disabled
              class="w-full disabled-input"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button 
          @click="dialogVisible = false"
          class="cancel-button"
          plain
        >
          取 消
        </el-button>
        <el-button 
          type="primary" 
          @click="submitForm" 
          :loading="formLoading"
          class="confirm-button"
        >
          确 定
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { AccountBalanceApi, AccountBalanceVO } from '@/api/juliang/accountbalance'
import { MerchantApi, MerchantVO } from '@/api/juliang/merchant'
import { Loading } from '@element-plus/icons-vue'
import { throttle, debounce } from 'lodash-es'

/** 账户余额 表单 */
defineOptions({ name: 'AccountBalanceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const merchantList = ref<MerchantVO[]>([]) // 商家列表
const merchantLoading = ref(false) // 商家列表加载状态
const hasMore = ref(true) // 是否还有更多数据
const loadingNewPage = ref(false) // 标记是否正在加载新页面
const searchKeyword = ref('') // 搜索关键字

const merchantQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantName: undefined as string | undefined
})

const formData = ref<{
  id: number | undefined
  merchantId: number | undefined
  advertiserId: number | undefined
  accountType: number | undefined
  balance: number | undefined
  frozenAmount: number | undefined
  status: number
  rechargeDiscountType?: number
  rebateRatio?: number
}>({
  id: undefined,
  merchantId: undefined,
  advertiserId: undefined,
  accountType: undefined,
  balance: undefined,
  frozenAmount: undefined,
  status: 0,
  rechargeDiscountType: undefined,
  rebateRatio: undefined,
})

const formRules = reactive({
  merchantId: [{ required: true, message: '商家不能为空', trigger: 'change' }],
  accountType: [{ required: true, message: '账户类型不能为空', trigger: 'change' }],
  advertiserId: [{ required: false, message: '巨量账户ID不能为空', trigger: 'blur' }],
  rechargeDiscountType: [{ required: true, message: '请选择充值折扣类型', trigger: 'change' }],
  rebateRatio: [
    { 
      validator: (rule: any, value: any, callback: any) => {
        // 只有主账号才能设置返利比例
        if (formData.value.accountType !== 1) {
          callback()
          return
        }
        
        if (value !== null && value !== undefined && value !== '') {
          const numValue = parseFloat(value)
          if (isNaN(numValue) || numValue < 0 || numValue > 100) {
            callback(new Error('返利比例必须在0-100之间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
})

const formRef = ref() // 表单 Ref

/** 获取商家详情 */
const getMerchantDetail = async (merchantId: number) => {
  try {
    return await MerchantApi.getMerchantById(merchantId)
  } catch (error) {
    console.error('获取商家详情失败:', error)
    return null
  }
}

/** 获取商家列表 */
const getMerchantList = async (isLoadMore = false) => {
  if (merchantLoading.value || (isLoadMore && !hasMore.value)) return
  
  if (isLoadMore) {
    loadingNewPage.value = true
  } else {
    merchantLoading.value = true
  }

  try {
    const data = await MerchantApi.getMerchantPage({
      pageNo: merchantQuery.pageNo,
      pageSize: merchantQuery.pageSize,
      merchantName: searchKeyword.value
    })
    
    if (data?.list?.length > 0) {
      // 如果是编辑状态，确保当前选中的商家保留在列表中
      if (isLoadMore && formType.value === 'update' && formData.value.merchantId) {
        const currentMerchant = merchantList.value.find(item => item.id === formData.value.merchantId)
        if (currentMerchant) {
          merchantList.value = [
            currentMerchant,
            ...merchantList.value.filter(item => item.id !== currentMerchant.id),
            ...data.list.filter(item => item.id !== currentMerchant.id)
          ]
        } else {
          merchantList.value = [...merchantList.value, ...data.list]
        }
      } else {
        merchantList.value = isLoadMore 
          ? [...merchantList.value, ...data.list]
          : data.list
      }
      hasMore.value = data.list.length === merchantQuery.pageSize
    } else {
      if (!isLoadMore) {
        // 如果是编辑状态，保留当前选中的商家
        if (formType.value === 'update' && formData.value.merchantId) {
          const currentMerchant = merchantList.value.find(item => item.id === formData.value.merchantId)
          merchantList.value = currentMerchant ? [currentMerchant] : []
        } else {
          merchantList.value = []
        }
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    message.error('获取商家列表失败')
    if (!isLoadMore) {
      merchantList.value = []
    }
  } finally {
    merchantLoading.value = false
    loadingNewPage.value = false
  }
}

/** 监听下拉框滚动 */
const handleDropdownScroll = throttle(async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 距离底部50px时预加载下一页
  if (scrollHeight - scrollTop - clientHeight < 50 && hasMore.value && !loadingNewPage.value) {
    merchantQuery.pageNo++
    await getMerchantList(true)
  }
}, 200)

/** 处理下拉框显示状态变化 */
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 下拉框显示时，添加滚动监听
    nextTick(() => {
      const dropdownWrapper = document.querySelector('.merchant-select-dropdown .el-select-dropdown__wrap')
      if (dropdownWrapper) {
        dropdownWrapper.addEventListener('scroll', handleDropdownScroll)
      }
    })
  } else {
    // 下拉框隐藏时，移除滚动监听
    const dropdownWrapper = document.querySelector('.merchant-select-dropdown .el-select-dropdown__wrap')
    if (dropdownWrapper) {
      dropdownWrapper.removeEventListener('scroll', handleDropdownScroll)
    }
    // 重置分页和搜索状态
    merchantQuery.pageNo = 1
    searchKeyword.value = ''
    hasMore.value = true
  }
}

/** 处理搜索 */
const handleSearch = debounce((query: string) => {
  searchKeyword.value = query.trim()
  merchantQuery.pageNo = 1
  hasMore.value = true
  merchantList.value = []
  getMerchantList()
}, 300)

/** 处理下拉框获得焦点 */
const handleSelectFocus = () => {
  if (merchantList.value.length === 0) {
    merchantQuery.pageNo = 1
    hasMore.value = true
    getMerchantList()
  }
}

/** 处理账户类型变化 */
const handleAccountTypeChange = () => {
  // 如果不是主账号，清空返利比例
  if (formData.value.accountType !== 1) {
    formData.value.rebateRatio = undefined
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  formLoading.value = true // 开启加载状态
  try {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    
    if (type === 'create') {
      // 新增时设置默认值
      formData.value.status = 0
      formData.value.balance = 0.0
      formData.value.frozenAmount = 0.0
      formLoading.value = false
      return
    }
    
    // 修改时，获取数据
    if (id) {
      // 获取账户余额数据
      const data = await AccountBalanceApi.getAccountBalanceById(id)
      formData.value = {
        ...data,
        merchantId: undefined, // 暂时清空商家ID
        // 处理返利比例数据转换（如果后端返回的是小数，转换为百分比）
        rebateRatio: data.rebateRatio && data.accountType === 1 ? (data.rebateRatio < 1 ? (data.rebateRatio * 100).toString() : data.rebateRatio.toString()) : undefined
      }
      
      // 如果有商家ID，获取商家详情
      if (data.merchantId) {
        const merchantDetail = await getMerchantDetail(data.merchantId)
        if (merchantDetail) {
          // 设置商家列表和选中值
          merchantList.value = [merchantDetail]
          formData.value.merchantId = merchantDetail.id
          
          // 获取更多商家列表用于选择
          try {
            const merchantData = await MerchantApi.getMerchantPage({
              pageNo: 1,
              pageSize: 10,
              merchantName: ''
            })
            
            if (merchantData?.list) {
              // 将其他商家添加到列表中
              merchantList.value = [
                merchantDetail,
                ...merchantData.list.filter(item => item.id !== merchantDetail.id)
              ]
              hasMore.value = merchantData.list.length === 10
            }
          } catch (error) {
            console.error('获取商家列表失败:', error)
            // 即使获取列表失败，也不影响当前商家的显示
          }
        }
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    merchantId: undefined,
    advertiserId: undefined,
    accountType: undefined,
    balance: undefined,
    frozenAmount: undefined,
    status: 0,
    rechargeDiscountType: undefined,
    rebateRatio: undefined,
  }
  // 重置商家相关的状态
  merchantList.value = []
  hasMore.value = true
  merchantQuery.pageNo = 1
  searchKeyword.value = ''
  formRef.value?.resetFields()
}

/** 验证主账号唯一性 */
const validateMainAccount = async () => {
  // 只有当账户类型为1（主账号）时才需要验证
  if (formData.value.accountType !== 1 || !formData.value.merchantId) {
    return true
  }
  
  try {
    // 调用API检查该商家是否已有主账号
    const data = await AccountBalanceApi.getAccountBalancePage({
      pageNo: 1,
      pageSize: 1,
      merchantId: formData.value.merchantId,
      accountType: 1
    })
    
    // 如果是编辑模式，排除当前编辑的记录
    if (formType.value === 'update' && formData.value.id) {
      const existingMainAccounts = data.list.filter(item => item.id !== formData.value.id)
      if (existingMainAccounts.length > 0) {
        message.error('该商家已存在主账号，一个商家只能有一个主账号')
        return false
      }
    } else {
      // 新增模式，直接检查是否存在
      if (data.list && data.list.length > 0) {
        message.error('该商家已存在主账号，一个商家只能有一个主账号')
        return false
      }
    }
    
    return true
  } catch (error) {
    console.error('验证主账号唯一性失败:', error)
    message.error('验证主账号唯一性失败，请重试')
    return false
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 验证主账号唯一性
  const isMainAccountValid = await validateMainAccount()
  if (!isMainAccountValid) {
    return
  }
  
  // 验证返利比例设置
  if (formData.value.accountType !== 1 && formData.value.rebateRatio) {
    message.error('只有主账号才能设置返利比例')
    return
  }
  
  // 验证充值折扣类型设置
  if (!formData.value.rechargeDiscountType) {
    message.error('请选择充值折扣类型')
    return
  }
  
  // 提交请求
  formLoading.value = true
  try {
    // 处理返利比例数据转换
    const submitData = {
      ...formData.value,
      rebateRatio: formData.value.rebateRatio && formData.value.accountType === 1 ? parseFloat(formData.value.rebateRatio.toString()) / 100 : undefined
    }
    
    if (formType.value === 'create') {
      // 新增时提交所有字段
      const createData = {
        ...submitData,
        balance: 0.0,
        frozenAmount: 0.0
      }
      await AccountBalanceApi.createAccountBalance(createData as unknown as AccountBalanceVO)
      message.success(t('common.createSuccess'))
    } else {
      // 修改时提交所有字段，包括余额和冻结金额
      const updateData = {
        ...submitData
      }
      await AccountBalanceApi.updateAccountBalance(updateData as unknown as AccountBalanceVO)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

<style lang="scss" scoped>
.account-balance-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    
    .el-dialog__header {
      padding: 20px 20px 0;
      margin: 0;
      
      .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .el-dialog__body {
      padding: 20px;
    }
    
    .el-dialog__footer {
      padding: 10px 20px 20px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
}

.account-balance-form {
  .form-item {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 500;
    }
    
    :deep(.el-input), 
    :deep(.el-select),
    :deep(.el-input-number) {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px var(--el-border-color) inset;
        
        &:hover {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
        
        &.is-focus {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }
    }
    
    .disabled-input {
      :deep(.el-input__wrapper) {
        background-color: var(--el-input-disabled-bg);
        
        &:hover {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
      
      :deep(.el-input-group__append) {
        color: var(--el-text-color-secondary);
        background-color: var(--el-input-disabled-bg);
        border-left: 1px solid var(--el-border-color);
      }
    }
    
    .radio-group {
      :deep(.el-radio) {
        margin-right: 20px;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
    
    .form-tip {
      margin-top: 4px;
      font-size: 12px;
      line-height: 1.4;
      color: var(--el-text-color-secondary);
    }
    
    :deep(.el-input-group__append) {
      color: var(--el-text-color-regular);
      background-color: var(--el-fill-color-light);
      border-left: 1px solid var(--el-border-color);
    }
    
    :deep(.el-form-item__content) {
      .el-input-group {
        width: 100%;
      }
    }
    
    :deep(.el-select) {
      width: 100%;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    :deep(.el-form-item__error) {
      font-size: 12px;
      color: var(--el-color-danger);
    }
    
    :deep(.el-form-item.is-required .el-form-item__label::before) {
      color: var(--el-color-danger);
    }
  }
  
  .w-full {
    width: 100%;
  }
}

.dialog-footer {
  text-align: right;
  
  .cancel-button,
  .confirm-button {
    min-width: 88px;
    padding: 8px 20px;
    font-size: 14px;
    border-radius: 4px;
    
    & + .el-button {
      margin-left: 12px;
    }
  }
}

.merchant-select-content {
  .merchant-empty {
    padding: 20px;
    text-align: center;
  }
  
  .merchant-loading {
    padding: 8px 0;
    text-align: center;
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
      color: var(--el-color-primary);
      vertical-align: middle;
    }
    
    .loading-text {
      font-size: 13px;
      color: var(--el-text-color-secondary);
      vertical-align: middle;
    }
  }
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-select-dropdown__list) {
  padding: 0;
}
</style>